package main

import (
	"encoding/json"
	redis2 "github.com/gomodule/redigo/redis"
	"github.com/robfig/cron"
	"go.uber.org/zap"
	"news/global"
	"news/initialize"
	"news/models"
	"news/router"
	"news/utils"
	"time"
)

func main() {

	//初始化路由
	Router := router.InitRouters()
	//初始化配置文件
	initialize.InitConfig()
	//初始化数据库
	initialize.InitMySQL()
	//定时采集数据
	Cron := cron.New() //创建一个cron实例

	var Redis = initialize.RedisConnect()

	//定时采集数据
	Cron.AddFunc("0 */6 * * * ?", func() {
		for key, values := range global.AllUrlAddress {
			switch key {
			case "a":
				global.QIanLong(values)
			case "b":
				global.BjNews(values)
			case "c":
				global.SouTHcn(values)
			case "d":
				global.NewsChina(values)
			case "e":
				global.ThePaper(values)
			//case "f":
			//	Cctv(values)
			case "g":
				global.Sina(values)
			}
		}
		for {
			getResult := <-global.Content
			if len(getResult) < 0 {
				return
			}
			for _, v := range getResult {
				var art models.Article
				title := utils.ReplaceAndTrim(v.Title, 166)
				if err := global.DB.Where("title = ?", title).First(&art); err.RowsAffected == 0 {
					if v.Title != "" && v.Content != "" {
						article := &models.Article{
							Title:      title,
							CategoryId: v.CategoryId,
							Url:        v.Url,
						}
						//写入主表
						global.DB.Create(article)
						//写入详情
						if article.ID > 0 {
							global.DB.Create(&models.ArticleDetail{
								Content:   v.Content,
								ArticleId: article.ID,
							})
						}
					}
				}
			}
		}
	})

	//更新栏目表文章总数
	err := Cron.AddFunc("*/50 * * * * ?", func() {
		var cate []models.Category
		global.DB.Model(&models.Category{}).Find(&cate)
		for _, v := range cate {
			var count int64
			global.DB.Model(&models.Article{}).Where("category_id = ?", v.ID).Count(&count)
			global.DB.Model(&models.Category{}).Where("id = ?", v.ID).Update("count", count)
		}
	})
	//更新统计信息
	err = Cron.AddFunc("*/50 * * * * ?", func() {
		////获取文章总数
		var count1 int64
		global.DB.Raw("SELECT sum(COUNT) from categories").Scan(&count1)
		//获取今天总数
		var count2 int64
		global.DB.Model(&models.Article{}).Where("add_time >= ?", time.Now().Format("2006-01-02")).Count(&count2)
		Redis.Do("HSet", global.WebsiteIndex, "count1", count1)
		Redis.Do("HSet", global.WebsiteIndex, "count2", count2)
		var cate []models.Category
		global.DB.Model(&models.Category{}).Find(&cate)
		jsonCate, _ := json.Marshal(cate)
		redis2.String(Redis.Do("Set", global.WebsiteCate, jsonCate))
	})

	if err != nil {
		zap.S().Debug("更新redis失败")
	}
	//启动/关闭
	Cron.Start()
	defer Cron.Stop()
	//加载模板
	Router.LoadHTMLGlob("views/*") //templates文件夹下所有模板文件
	//静态文件目录
	Router.Static("/static", "./static")
	Router.Run(":8081")
}
